package com.Servlet;

import com.JavaBean.BookBean;
import com.JavaBean.BookDAO;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.SQLException;

@WebServlet(value = "/query")
public class BookQueryServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        String bookId = request.getParameter("bookId");
        try{
            BookDAO bookDAO = new BookDAO();
            BookBean bookBean = bookDAO.search(bookId);
            if (bookBean !=null){
                request.getSession().setAttribute("book",bookBean);
                RequestDispatcher viewDispatcher = request.getRequestDispatcher("jsp/display.jsp");
                viewDispatcher.forward(request, response);
            }
            else {
                RequestDispatcher viewDispatcher = request.getRequestDispatcher("jsp/errorPage.jsp");
                viewDispatcher.forward(request, response);
            }
        } catch (SQLException |ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
